/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package magazynapp.forms;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import magazynapp.forms.MagazynMainPanel.MagazynModule;


/**
 *
 * @author TEMP
 */
public class MagazynModuleImpl implements MagazynModule {

    public boolean addProduct(String nazwa, String opis, String kategoria, String jednostkaMiary, int ilosc, Date dataDostawy, String lokalizacja, String numerSeryjny, String model, String dystrybutor) {

        try {
            Random rand = new Random();
            Serializer serializer = new Serializer();

            String folderPath = new String();
            if(kategoria.equals("produkt"))
            {
                folderPath = "c:/pzietek/produkty/";
            }
            else {
                folderPath = "c:/pzietek/produkty zlozone/";
            }

            File[] files = serializer.getFiles(folderPath);

            Product produkt = null;

            boolean found = false;
            if(files != null)
            {
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];

                    String fullName = file.getName();
                    String shortName = fullName.substring(0, fullName.length()-4);
                    int tempId = Integer.parseInt(shortName);
                    String path = serializer.getFilePath(String.valueOf(tempId),folderPath);

                    if(kategoria.equals("produkt"))
                    {
                        Product p  = serializer.readProduct(path);
                        produkt = p;
                    }
                    else {
                        ProductDetailed pd= serializer.readProductDetailed(path);
                        produkt = pd;
                    }

                    if(produkt.nazwa.compareTo(nazwa) == 0)
                    {
                        found = true;
                    }
                }

            }

            if(!found) {
                if(kategoria.equals("produkt"))
                {
                    Product p = new Product(nazwa, opis, kategoria, jednostkaMiary, dataDostawy, lokalizacja);

                    p.id = rand.nextInt(100);

                    serializer.write(p, "c:/pzietek/produkty/"+p.id+".xml");
                    produkt = p;
                }
                else
                {
                    ProductDetailed pd = new ProductDetailed(nazwa, opis, "produkt2", jednostkaMiary, ilosc, dataDostawy, lokalizacja, numerSeryjny, model, dystrybutor);
                    pd.id = rand.nextInt(100);

                    serializer.write(pd, "c:/pzietek/produkty zlozone/"+pd.id+".xml");
                    produkt = pd;
                }
            }
            
            ActionHistory ah = new ActionHistory(rand.nextInt(10000), "ADD_PRODUCT", ilosc, "tarni", produkt.id, produkt.kategoria, dataDostawy);
            serializer = new Serializer();
            serializer.write(ah, "c:/pzietek/historia/"+ah.id+".xml");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

   public String[][] searchProducts(String kategoria, String nazwa) {

        try {
            String[][] products = null;
            Serializer serializer = new Serializer();

            String folderPath = new String();
            if(kategoria.equals("produkt"))
            {
                folderPath = "c:/pzietek/produkty/";
            }
            else {
                folderPath = "c:/pzietek/produkty zlozone/";
            }

            File[] files = serializer.getFiles(folderPath);

            if(files != null)
            {
                int idx = 0;
                products = new String[files.length][4];
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];

                    String fullName = file.getName();
                    String shortName = fullName.substring(0, fullName.length()-4);
                    int tempId = Integer.parseInt(shortName);
                    String path = serializer.getFilePath(String.valueOf(tempId),folderPath);

                    Product produkt = null;

                    if(kategoria.equals("produkt"))
                    {
                        Product p  = serializer.readProduct(path);
                        produkt = p;
                    }
                    else {
                        ProductDetailed pd= serializer.readProductDetailed(path);
                        produkt = pd;
                    }

                    if(produkt.nazwa.equals(nazwa))
                    {
                       // products.add(produkt);
                        products[idx] = produkt.toStringTab();
                        idx ++;
                    } else if(nazwa==null || nazwa.equals("")){
                        products[idx] = produkt.toStringTab();
                        idx ++;
                    }
                }
            }

            return products;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    public String[][] searchProducts(String kategoria, String nazwa, Date dataMagazynowania) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = null;
        String date2 = null;

        try {
            String[][] products = null;
            Serializer serializer = new Serializer();

            String folderPath = new String();
            if(kategoria.equals("produkt"))
            {
                folderPath = "c:/pzietek/produkty/";
            }
            else {
                folderPath = "c:/pzietek/produkty zlozone/";
            }

            File[] files = serializer.getFiles(folderPath);

            if(files != null)
            {
                int idx = 0;
                products = new String[files.length][4];
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];

                    String fullName = file.getName();
                    String shortName = fullName.substring(0, fullName.length()-4);
                    int tempId = Integer.parseInt(shortName);
                    String path = serializer.getFilePath(String.valueOf(tempId),folderPath);

                    Product produkt = null;

                    if(kategoria.equals("produkt"))
                    {
                        Product p  = serializer.readProduct(path);
                        produkt = p;
                    }
                    else {
                        ProductDetailed pd= serializer.readProductDetailed(path);
                        produkt = pd;
                    }

                    if(dataMagazynowania!=null){
                        date1 = sdf.format(produkt.dataDostawy);
                        date2 = sdf.format(dataMagazynowania);
                        System.out.println("Data magazynowania" + dataMagazynowania.toString());
                        
                        if(produkt.nazwa.equals(nazwa) && produkt.kategoria.equals(kategoria) && date1.equals(date2))
                        {
                            products[idx] = produkt.toStringTab();
                            idx ++;
                        } else if((nazwa==null || nazwa.equals("")) && produkt.kategoria.equals(kategoria) && date1.equals(date2)){
                            products[idx] = produkt.toStringTab();
                            idx ++;
                        } else if(produkt.nazwa.equals(nazwa) && (kategoria==null || kategoria.equals("")) && date1.equals(date2)){
                            products[idx] = produkt.toStringTab();
                            idx ++;
                        } else if((nazwa==null || nazwa.equals("")) && (kategoria==null || kategoria.equals("")) && date1.equals(date2)){
                            products[idx] = produkt.toStringTab();
                            idx ++;
                        }
                    } else if(produkt.nazwa.equals(nazwa) && produkt.kategoria.equals(kategoria)){
                        products[idx] = produkt.toStringTab();
                        idx ++;
                    } else if((nazwa==null || nazwa.equals("")) && produkt.kategoria.equals(kategoria)){
                        products[idx] = produkt.toStringTab();
                        idx ++;
                    } else if(produkt.nazwa.equals(nazwa) && (kategoria==null || kategoria.equals(""))){
                        products[idx] = produkt.toStringTab();
                        idx ++;
                    }
                }
            }

            return products;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String[][] getActionHistory(Date from, Date to) {
        try {
            
            Serializer serializer = new Serializer();

            String folderPath = "c:/pzietek/historia/";
            String[][] resultList = null;
            File[] files = serializer.getFiles(folderPath);
            if(files != null)
            {
                resultList = new String[files.length][4];
                for (int i = 0; i < files.length; i++) {

                    File file = files[i];
                    String fullName = file.getName();
                    String shortName = fullName.substring(0, fullName.length()-4);

                    String path = serializer.getFilePath(shortName,folderPath);

                    ActionHistory ah = serializer.readActionHistory(path);

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    System.out.println("TEST AH ="+ah.id);

                    System.out.println("DATA AH =" +sdf.format(ah.dataAkcji));
                    System.out.println("DATA FROM =" +sdf.format(from));
                    System.out.println("DATA TO =" +sdf.format(to));
                    if(ah.dataAkcji.after(from) && ah.dataAkcji.before(to))
                    {
                       // resultList.add(ah);
                        System.out.println("WLAZLEM!");
                        resultList[i] = ah.toStringTab();
                    }
                    System.out.println("WYLAZLEM");
                }
            }
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean createSnapshotPoint(Date data) {

        try {

            Serializer serializer = new Serializer();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String folderPath = "c:/pzietek/historia/";

            Random rand = new Random();
            Snapshot snap = new Snapshot();

            snap.id = rand.nextInt(1000);
            snap.data = data;

            Snapshot oldOne = serializer.getNewestSnapshot();
            List<SnapshotDetails> spds = null;
            if(oldOne == null)
            {
                snap.sumaWszystkichProduktow = 0;
                spds = new ArrayList<SnapshotDetails>();
            }
            else
            {
                snap.sumaWszystkichProduktow = oldOne.sumaWszystkichProduktow;
                spds = oldOne.listaProduktow;
            }

            File[] files = serializer.getFiles(folderPath);
            if(files != null)
            {
                for (int i = 0; i < files.length; i++) {

                    File file = files[i];

                    String fullName = file.getName();
                    String shortName = fullName.substring(0, fullName.length()-4);

                    int idTemp = Integer.parseInt(shortName);
                    System.out.println(shortName);
                    String path = serializer.getFilePath(String.valueOf(idTemp),folderPath);

                    ActionHistory ah = serializer.readActionHistory(path);

                    if(ah.dataAkcji.before(data)) {
                        boolean found = false;
                        for (SnapshotDetails spd : spds) {
                            if(spd.produktId == ah.produktId)
                            {
                                found = true;
                                if(ah.typAkcji.equals("ADD_PRODUCT")) {
                                    spd.produktIlosc += ah.ilosc;
                                    snap.sumaWszystkichProduktow += ah.ilosc;
                                }
                                else
                                {
                                    spd.produktIlosc -= ah.ilosc;
                                    snap.sumaWszystkichProduktow -= ah.ilosc;
                                }
                            }
                        }
                        if(!found)
                        {
                             SnapshotDetails spda = new SnapshotDetails();
                             spda.id = rand.nextInt(1000);
                             spda.produktId = ah.produktId;
                             spda.produktIlosc = 0;
                             if(ah.typAkcji.equals("ADD_PRODUCT")) {
                                spda.produktIlosc += ah.ilosc;
                                snap.sumaWszystkichProduktow += ah.ilosc;
                             }
                             else
                             {
                                spda.produktIlosc -= ah.ilosc;
                                snap.sumaWszystkichProduktow -= ah.ilosc;
                             }
                             spds.add(spda);
                        }
                        file.delete();
                    }                    
                }
            }
            snap.listaProduktow = spds;
            serializer.write(snap, "c:/pzietek/snapshot/"+sdf.format(data)+".xml");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
 
    }

    public boolean delProduct(int id, String kategoria, int ilosc, String przyczyna) {
        try {
            Random rand = new Random();
            Serializer serializer = new Serializer();

            ActionHistory ah = new ActionHistory(rand.nextInt(10000), "DEL_PRODUCT", ilosc, "tarni", id, kategoria, new Date());
            serializer = new Serializer();
            serializer.write(ah, "c:/pzietek/historia/"+ah.id+".xml");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    class ActionHistory implements Serializable {

        public int id;
        public String typAkcji;
        public int ilosc;
        public String userName;
        public int produktId;
        public String kategoria;
        public Date dataAkcji;

        public ActionHistory() {
        }

        public ActionHistory(int id, String typAkcji, int ilosc, String userName, int produktId, String kategoria, Date dataAkcji) {
            this.id = id;
            this.typAkcji = typAkcji;
            this.ilosc = ilosc;
            this.userName = userName;
            this.produktId = produktId;
            this.kategoria = kategoria;
            this.dataAkcji = dataAkcji;
        }

        public String[] toStringTab()
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            String[] result = new String[4];

            result[0] = String.valueOf(this.produktId);
            result[1] = this.typAkcji;
            result[2] = String.valueOf(this.ilosc);
            result[3] = sdf.format(this.dataAkcji);

            return result;
        }
    }

    class Product implements Serializable {

        public int id;
        public String nazwa;
        public String opis;
        public String kategoria;
        public String jednostkaMiary;

        public Date dataDostawy;
        public String lokalizacja;

        public Product() {
        }

        public Product(String nazwa, String opis, String kategoria, String jednostkaMiary, Date dataDostawy, String lokalizacja) {
            this.nazwa = nazwa;
            this.opis = opis;
            this.kategoria = kategoria;
            this.jednostkaMiary = jednostkaMiary;
            
            this.dataDostawy = dataDostawy;
            this.lokalizacja = lokalizacja;
        }

        public String[] toStringTab()
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            String[] result = new String[4];

            result[0] = this.nazwa;
            result[1] = String.valueOf(this.id);
            result[2] = this.kategoria;
            result[3] = sdf.format(this.dataDostawy);

            return result;
        }

    }

    class ProductDetailed extends Product implements Serializable {

        public String numerSeryjny;
        public String model;
        public String dystrybutor;

        public ProductDetailed() {
        }

        public ProductDetailed(String nazwa, String opis, String kategoria, String jednostkaMiary, int ilosc, Date dataDostawy, String lokalizacja, String numerSeryjny, String model, String dystrybutor) {
            super(nazwa, opis, kategoria, jednostkaMiary, dataDostawy, lokalizacja);
            this.numerSeryjny = numerSeryjny;
            this.model = model;
            this.dystrybutor = dystrybutor;
        }
    }

    class Snapshot implements Serializable {

        public int id;
        public Date data;
        public List<SnapshotDetails> listaProduktow;
        public int sumaWszystkichProduktow;

        public Snapshot() {
        }

        public Snapshot(int id, Date data, List<SnapshotDetails> listaProduktow, int sumaWszystkichProduktow) {
            this.id = id;
            this.data = data;
            this.listaProduktow = listaProduktow;
            this.sumaWszystkichProduktow = sumaWszystkichProduktow;
        }
    }

    class SnapshotDetails implements Serializable {

        public int id;
        public int produktId;
        public int produktIlosc;

        public SnapshotDetails() {
        }

        public SnapshotDetails(int id, int produktId, int produktIlosc) {
            this.id = id;
            this.produktId = produktId;
            this.produktIlosc = produktIlosc;
        }
    }

    class Serializer {

    XStream xs;

    private Serializer() {
        this.xs  = new XStream(new DomDriver());
        this.xs.alias("ActionHistory", ActionHistory.class);
        this.xs.alias("Product", Product.class);
        this.xs.alias("ProductDetailed", ProductDetailed.class);
        this.xs.alias("Snapshot", Snapshot.class);
        this.xs.alias("SnapshotDetails", SnapshotDetails.class);
    }


    public Snapshot getNewestSnapshot()
    {
          try {

            Serializer serializer = new Serializer();
            String folderPath = "c:/pzietek/snapshot/";

            Snapshot snap = null;

            long max = 0;

            File[] files = serializer.getFiles(folderPath);
            if(files != null)
            {
                for (int i = 0; i < files.length; i++) {

                    File file = files[i];

                    String fullName = file.getName();
                    String shortName = fullName.substring(0, fullName.length()-4);

                    long idTemp = Long.parseLong(shortName);

                    if(idTemp > max)
                    {
                        max = idTemp;
                    }
                }

                String snapId = String.valueOf(max);

                snap = (Snapshot)serializer.readSnapshot(folderPath + snapId + ".xml");
            }



            return snap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public String getFilePath(String fileName, String path)
    {
        try {

            File dir = new File(path);

            if(dir.isDirectory()) {
                File[] files = dir.listFiles();


                for (int i = 0; i < files.length; i++) {
                    File file = files[i];


                    String fullName = file.getName();
                    String shortName = fullName.substring(0, fullName.length()-4);

                    if(shortName.compareTo(fileName) == 0) {
                        return file.getPath();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

     public File[] getFiles(String path)
    {
        try {


            File dir = new File(path);


            if(dir.isDirectory()) {
                File[] files = dir.listFiles();
                return files;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public void write(Serializable object, String path)
    {
        try {

            FileOutputStream fs = new FileOutputStream(path);
            xs.toXML(object, fs);
            fs.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Product readProduct(String path)
    {
        try {

            FileInputStream fis = new FileInputStream(path);
            Product p = new Product();
            p = (Product) xs.fromXML(fis,p);
            fis.close();
            return p;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public ActionHistory readActionHistory(String path)
    {
        try {

            FileInputStream fis = new FileInputStream(path);
            ActionHistory p = new ActionHistory();
            p = (ActionHistory) xs.fromXML(fis,p);
            fis.close();
            return p;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public ProductDetailed readProductDetailed(String path)
    {
        try {
            FileInputStream fis = new FileInputStream(path);
            ProductDetailed p = new ProductDetailed();
            p = (ProductDetailed) xs.fromXML(fis,p);
            fis.close();
            return p;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

        public Snapshot readSnapshot(String path)
    {
        try {
            FileInputStream fis = new FileInputStream(path);
            Snapshot p = new Snapshot();
            p = (Snapshot) xs.fromXML(fis,p);
            fis.close();
            return p;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public SnapshotDetails readSnapshotDetails(String path)
    {
        try {
            FileInputStream fis = new FileInputStream(path);
            SnapshotDetails p = new SnapshotDetails();
            p = (SnapshotDetails) xs.fromXML(fis,p);
            fis.close();
            return p;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

}
